<template>
  <div>
    <el-dialog title="轮播图管理" :visible.sync="visible">
      <el-button type="primary" @click="submit">保存并关闭</el-button>
      <el-button icon="el-icon-circle-plus-outline" @click="rollImageData.push({name:'',image:''})">添加轮播图</el-button>
      <div v-for="(item,index) in rollImageData" :key="item" style="margin: 5px;">
        <div style="display: flex;align-items: center;">
          <div style="margin: 5px;">轮播图 {{ index+1 }}</div>
          <el-button icon="el-icon-circle-minus-outline"
            @click="rollImageData.splice(index,1)">删除该轮播图</el-button>
        </div>
        <div style="display: flex;align-items: center;margin: 10px;">
          <div style="width: 40px;">标题:</div><el-input v-model="item.name" placeholder="请输入内容"></el-input>
        </div>
        <div>
          <UploadComponent :image-limit="1" @handleUpload="handleImageUpload(index,$event)" ref="imageUpload">
          </UploadComponent>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRollImage, rollImageSubmit } from '@/api/leaseManage'
import UploadComponent from './UploadComponent.vue'
export default {
  components: { UploadComponent },
  data(){
    return{
      visible:false,
      rollImageData:[],

    }
  }
  ,
  methods:{
    handleImageUpload(index,urls) {
      if (urls.length === 0) this.rollImageData[index].image = ''
      else this.rollImageData[index].image = urls[0].image
    },
    async submit(){
      if (this.rollImageData.length >= 4 || this.rollImageData.length==0){
        this.$message('轮播图不应超过3张,也不应为0张')
        return 
      }
      for(let i=0;i<this.rollImageData.length;i++){
        if(this.rollImageData[i].name.trim().length<3){
          this.$message('轮播图标题应大于3个字')
          return
        }
        else if (this.rollImageData[i].image.trim().length===0){
          this.$message('轮播图图片不应空白')
          return
        }
      }
      let res=await rollImageSubmit(this.rollImageData)
      if (res.data.code === 1) {
        this.$message({message: '轮播图上传成功',type: 'success'})
        this.visible=false
      }
    },
    async getRollImageData(){
      let res= await getRollImage()
      this.rollImageData=res.data.data
      this.initUpload()
    },
    initUpload() {
      console.log(this.rollImageData)
      this.$nextTick(()=>{
        for(let i=0;i<this.rollImageData.length;i++){
          this.$refs['imageUpload'][i].initImages(this.rollImageData[i].image)
        }
      })
      
    },
  },
  model: {
    prop: 'rollImageVisible',
    event: 'change'
  },
  props: {
    rollImageVisible: {
      type: Boolean
    }
  },
  watch:{
    'rollImageVisible':{
      handler(newVal){
        this.visible=newVal
      }
    },
    'visible':{
      handler(newVal){
        this.$emit('change',newVal)
        this.getRollImageData()
      }
    }


  }
}
</script>

<style>

</style>